package com.sikao.app.dao;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.sikao.app.bean.UploadPicturesBean;
import com.sikao.app.net.HttpApi;
import com.sikao.app.net.OkHttpHelper;
import com.sikao.app.net.OnNetBackListener;
import com.sikao.app.net.SpotsCallBack;
import com.sikao.app.utils.BitmapUtils;
import com.squareup.okhttp.Response;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static android.R.attr.path;
import static android.R.id.list;
import static com.baidu.location.h.b.i;

/**
 * Created by y50 on 2016/4/27.
 */
public class UploadPicturesModel extends BaseModel {

	private List<String> list;

	public UploadPicturesModel(Context context, OnNetBackListener listener) {
		super(context, listener);
	}


	@Override
	public void request(String data, boolean isShow) {
		Map<String, String> params = new HashMap<>();
		params.put(data, data);
		request(params, isShow);
	}

	public void request(final Map<String, String> params, boolean isShow) {
		list = new ArrayList<>();
		for (Map.Entry<String, String> entry : params.entrySet()) {
			entry.getValue();
			String path = BitmapUtils.bitmapFileZoom(entry.getValue());
			//是否压缩了，压缩过为yes，否则为no
			if (entry.getValue() != null && path.equals(entry.getValue())) {
				list.add("no");
			} else {
				list.add("yes");
				entry.setValue(path);
			}
		}
		OkHttpHelper.getInstance().postPictures(HttpApi.UPLOAD_PICTURE_URL, params, new SpotsCallBack<UploadPicturesBean>(context, isShow) {
			@Override
			public void onSuccess(Response response, UploadPicturesBean result) {
				onNetBackListener.netBack(result);
				int i = 0;
				for (Map.Entry<String, String> entry : params.entrySet()) {
					if (!list.get(i).equals("yes")) {
						return;
					}
					String path = entry.getValue();
					File file = new File(path);
					if (file.exists()) {
						file.delete();
					}
				}
			}

			@Override
			public void onError(Response response, int code, Exception e) {
				onNetBackListener.netBack(null);
				int i = 0;
				for (Map.Entry<String, String> entry : params.entrySet()) {
					if (!list.get(i).equals("yes")) {
						return;
					}
					String path = entry.getValue();
					File file = new File(path);
					if (file.exists()) {
						file.delete();
					}
				}
			}
		});
	}

}
